// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

Ajax.Autocompleter.prototype.oldOnClick = Ajax.Autocompleter.prototype.onClick;

Ajax.Autocompleter.prototype.onClick = function(event) {
    var tagName = event.target? event.target.tagName : event.srcElement.tagName;
    if (tagName == "IMG") {
        var element = Event.findElement(event, 'LI');
        this.index = element.autocompleteIndex;
        this.updateElement(this.getCurrentEntry(), true);
        this.element.value += ":";
        
        this.changed = true;
        this.hasFocus = true;

        if(this.observer) clearTimeout(this.observer);
        this.observer = setTimeout(this.onObserverEvent.bind(this), this.options.frequency*500);
    } else {
        this.oldOnClick(event);
    }
}

Ajax.Autocompleter.prototype.updateElement = function(selectedElement, loseFocus) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');

    var lastTokenPos = this.findLastToken();
    if (lastTokenPos != -1) {
      var newValue = this.element.value.substr(0, lastTokenPos + 1);
      var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value;
    } else {
      this.element.value = value;
    }
    if (!loseFocus) this.element.focus();

    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
}
